package com.gmadmin.websocket.handler;

import cn.hutool.json.JSONUtil;
import com.gmadmin.utils.SecurityUtils;
import com.gmadmin.utils.StringUtils;
import com.gmadmin.websocket.WsSessionManager;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2022/8/1 18:53
 * ws消息处理类
 */
@Component
public class CustomWsHandler extends AbstractWebSocketHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(CustomWsHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        LOGGER.info("建立ws连接用户id:{}", StringUtils.getParamByUrl(session.getUri().toString(), "userID"));

        String key = StringUtils.getParamByUrl(session.getUri().toString(), "userID");
        WsSessionManager.add(key, session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        LOGGER.info("发送文本消息");
        // 获得客户端传来的消息
        String payload = message.getPayload();
        LOGGER.info("server 接收到消息 " + payload);
        session.sendMessage(new TextMessage(payload));
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        LOGGER.info("发送二进制消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        LOGGER.error("异常处理");
        WsSessionManager.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        LOGGER.info("关闭ws连接");
        WsSessionManager.removeAndClose(session.getId());
    }

}
